//
//  ChangeMobileViewController.m
//  HQJFacilitator
//
//  Created by mymac on 2016/10/20.
//  Copyright © 2016年 Fujian first time iot technology investment co., LTD. All rights reserved.
//

#import "ChangeMobileViewController.h"

@interface ChangeMobileViewController ()
@property (nonatomic,strong)UIButton *okBtn;
@property (nonatomic,strong)UILabel *promptLabel;
@property (nonatomic,strong)UILabel *NewMobileLabel;
@property (nonatomic,strong)UILabel *tradingPswLabel;
@property (nonatomic,strong)UITextField *codeTextField;
@property (nonatomic,strong)JKCountDownButton *codeBtn;
@property (nonatomic,strong)UIImageView *titleImageView;
@property (nonatomic,strong)UITextField *NewMobileTextField;
@property (nonatomic,strong)UITextField *tradingPswTextField;
@property (nonatomic,strong)UILabel *idLabel;
@property (nonatomic,strong)UITextField *idTextField;
@property (nonatomic,assign)BOOL isMobileOk;

@end

@implementation ChangeMobileViewController

-(UIImageView *)titleImageView {
    if (!_titleImageView) {
        _titleImageView = [[UIImageView alloc]init];
        _titleImageView.layer.masksToBounds = YES;
        _titleImageView.layer.cornerRadius = 7.5;
        _titleImageView.image =[UIImage imageNamed:@"zhuyi"];
        [self.view addSubview:_titleImageView];
    }
    
    
    return _titleImageView;
}
-(UILabel *)promptLabel {
    if(!_promptLabel){
        _promptLabel =[[UILabel alloc]init];
        _promptLabel.textColor = [ManagerEngine getColor:@"f54949"];
        _promptLabel.font = [UIFont systemFontOfSize:12];
        _promptLabel.numberOfLines = 0;
        [self.view addSubview:_promptLabel];
        
        
    }
    return _promptLabel;
}
-(UILabel *)NewMobileLabel {
    if (!_NewMobileLabel) {
        _NewMobileLabel =[[UILabel alloc]init];
        _NewMobileLabel.font =[UIFont systemFontOfSize:17];
        _NewMobileLabel.textColor =[ManagerEngine getColor:@"323232"];
        _NewMobileLabel.text = @"新手机号:";
        [self.view addSubview:_NewMobileLabel];
    }
    
    
    return _NewMobileLabel;
}
-(UITextField *)NewMobileTextField {
    
    if (!_NewMobileTextField) {
        
        _NewMobileTextField = [[UITextField alloc]init];
        _NewMobileTextField.placeholder = @"请输入新的手机号码";
        _NewMobileTextField.clearButtonMode = UITextFieldViewModeAlways;
        _NewMobileTextField.font = [UIFont systemFontOfSize:15];
        _NewMobileTextField.keyboardType = UIKeyboardTypeNumberPad;
        _NewMobileTextField.borderStyle = UITextBorderStyleRoundedRect;
        [self.view addSubview:_NewMobileTextField];
        
        
    }
    
    return _NewMobileTextField;
}
-(UITextField *)codeTextField {
    if(!_codeTextField ){
        _codeTextField =[[UITextField alloc]init];
        _codeTextField.placeholder =@"请输入验证码";
        _codeTextField.font = [UIFont systemFontOfSize:15];
        _codeTextField.keyboardType = UIKeyboardTypeNumberPad;
        _codeTextField.borderStyle = UITextBorderStyleRoundedRect;
        [self.view addSubview:_codeTextField];

    }
    return _codeTextField;
}

-(JKCountDownButton *)codeBtn {
    if (!_codeBtn) {
        _codeBtn = [JKCountDownButton buttonWithType:UIButtonTypeCustom];
        [_codeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        _codeBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        _codeBtn.layer.masksToBounds = YES;
        _codeBtn.layer.cornerRadius = 5;
        _codeBtn.backgroundColor = [ManagerEngine getColor:@"00ccb8"];
        [self.view addSubview:_codeBtn];
    }
    return _codeBtn;
}

-(UILabel *)idLabel {
    if (!_idLabel) {
        _idLabel = [[UILabel alloc]init];
        _idLabel.text = @"身份证:";
        _idLabel.font = [UIFont systemFontOfSize:17];
        _idLabel.textColor = [ManagerEngine getColor:@"323232"];
        [self.view addSubview:_idLabel];
    }
    
    
    return _idLabel;
}


-(UITextField *)idTextField {
    if (!_idTextField) {
        _idTextField = [[UITextField alloc]init];
        _idTextField.clearButtonMode = UITextFieldViewModeAlways;
        _idTextField.keyboardType = UIKeyboardTypeASCIICapable;
        _idTextField.borderStyle = UITextBorderStyleRoundedRect;
        _idTextField.font = [UIFont systemFontOfSize:15];
        _idTextField.placeholder = @"请输入身份证";
        [self.view addSubview:_idTextField];
        
    }
    
    
    return _idTextField;
}

-(UILabel *)tradingPswLabel {
    if (!_tradingPswLabel) {
        _tradingPswLabel =[[UILabel alloc]init];
        _tradingPswLabel.text = @"交易密码:";
        _tradingPswLabel.font = [UIFont systemFontOfSize:17];
        _tradingPswLabel.textColor = [ManagerEngine getColor:@"323232"];
        [self.view addSubview:_tradingPswLabel];
    }
    
    
    return _tradingPswLabel;
}

-(UITextField *)tradingPswTextField {
    
    if (!_tradingPswTextField) {
        _tradingPswTextField = [[UITextField alloc]init];
        
        _tradingPswTextField.placeholder =@"请输入交易密码";
        _tradingPswTextField.secureTextEntry = YES;
        _tradingPswTextField.clearButtonMode = UITextFieldViewModeAlways;
        _tradingPswTextField.keyboardType = UIKeyboardTypeNumberPad;
        _tradingPswTextField.borderStyle = UITextBorderStyleRoundedRect;
        [self.view addSubview:_tradingPswTextField];
    }
    
    
    return _tradingPswTextField;
}

-(UIButton *)okBtn {
    if (!_okBtn) {
        _okBtn =[UIButton buttonWithType:UIButtonTypeCustom];
        _okBtn.backgroundColor =[ManagerEngine getColor:@"8ae6dc"];
        _okBtn.layer.masksToBounds = YES;
        _okBtn.layer.cornerRadius = 5;
        _okBtn.titleLabel.font = [UIFont systemFontOfSize:16];
        [_okBtn setTitle:@"确定" forState:UIControlStateNormal];
        [self.view addSubview:_okBtn];
    }
    
    
    return _okBtn;
}

#pragma mark --
#pragma mark ---试图创建
-(void)addUI {
    self.titleImageView.sd_layout.leftSpaceToView(self.view,EDGE).topSpaceToView(self.view,EDGE+NAVHEIGHT).heightIs(15).widthIs(15);
    
    
    self.promptLabel.text = [NSString stringWithFormat:@"当前手机号是%@，如果您本次修改成功，相对应的会员账号的手机号也将同步修改。",Mmobile];
     CGRect PromptFrame = [self.promptLabel.text boundingRectWithSize:CGSizeMake(WIDTH-(EDGE*2)-15-5, 1000)options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:12]} context:nil];
    [ManagerEngine setTextColor:self.promptLabel FontNumber:[UIFont systemFontOfSize:12] AndRange:Mmobile AndColor:[ManagerEngine getColor:@"00ccb8"]];
    self.promptLabel.sd_layout.leftSpaceToView(self.titleImageView,5).topEqualToView(self.titleImageView).heightIs(PromptFrame.size.height).widthIs(WIDTH-(EDGE*2)-15-5);
    
    
    CGFloat mobileSize = [ManagerEngine setTextWidthStr:self.NewMobileLabel.text andFont:[UIFont systemFontOfSize:17]];
    self.NewMobileLabel.sd_layout.leftEqualToView(self.titleImageView).topSpaceToView(self.promptLabel,30).heightIs(20).widthIs(mobileSize);
    
    self.NewMobileTextField.sd_layout.leftSpaceToView(self.NewMobileLabel,5).topSpaceToView(self.promptLabel,20).heightIs(44).widthIs(WIDTH-(EDGE*2)-5-mobileSize);
    
    self.codeTextField.sd_layout.leftEqualToView(self.titleImageView).topSpaceToView(self.NewMobileTextField,20).heightIs(44).widthIs(WIDTH -100-(EDGE*2)-10);
    
    self.codeBtn.sd_layout.leftSpaceToView(self.codeTextField,10).topEqualToView(self.codeTextField).heightIs(44).widthIs(100);
    
    CGFloat IDSize = [ManagerEngine setTextWidthStr:self.idLabel.text andFont:[UIFont systemFontOfSize:17]];
    self.idLabel.sd_layout.leftEqualToView(self.titleImageView).topSpaceToView(self.codeTextField,30).heightIs(20).widthIs(IDSize);
     self.idTextField.sd_layout.leftSpaceToView(self.idLabel,5).topSpaceToView(self.codeTextField,20).heightIs(44).widthIs(WIDTH-(EDGE*2)-5-IDSize);
    
    
    CGFloat tradingPswSize = [ManagerEngine setTextWidthStr:self.tradingPswLabel.text andFont:[UIFont systemFontOfSize:17]];
    self.tradingPswLabel.sd_layout.leftEqualToView(self.titleImageView).topSpaceToView(self.idLabel,45).heightIs(20).widthIs(tradingPswSize);
    self.tradingPswTextField.sd_layout.leftSpaceToView(self.tradingPswLabel,5).topSpaceToView(self.idTextField,20).heightIs(44).widthIs(WIDTH-(EDGE*2)-5-tradingPswSize);
    
    self.okBtn.sd_layout.leftEqualToView(self.titleImageView).topSpaceToView(self.tradingPswTextField,30).heightIs(44).widthIs(WIDTH-(EDGE*2));
}

#pragma mark --
#pragma mark ---信号创建
-(void)initSignal {
    
    RACSignal *newMoileSignal = [self.NewMobileTextField.rac_textSignal map:^id(id value) {
        return @([ManagerEngine valiMobile:value]);
    }];
    RACSignal *codeSignal = [self.codeTextField.rac_textSignal map:^id(id value) {
        return @([self codeValid:value]);
    }];
    
    RACSignal *pswSignal = [self.tradingPswTextField.rac_textSignal map:^id(id value) {
        return @([self pswValid:value]);
    }];
    
    RACSignal *idSignal = [self.idTextField.rac_textSignal map:^id(id value) {
        return @([ManagerEngine validateIdentityCard:value]);
    }];
    
    
    RACSignal *mergeSignal= [RACSignal combineLatest:@[newMoileSignal,codeSignal,pswSignal,idSignal]reduce:^id(NSNumber *MoileValid,NSNumber *codeValid,NSNumber *pswValid,NSNumber *idValid){
        return @([MoileValid boolValue]&&[codeValid boolValue]&&[pswValid boolValue]&&[idValid boolValue]);
    }];
    
    
    
    
    
    [mergeSignal subscribeNext:^(NSNumber *x) {
        self.okBtn.enabled = [x boolValue];
        if ([x boolValue]) {
            self.okBtn.backgroundColor = [ManagerEngine getColor:@"00ccb8"];
        } else {
            
            self.okBtn.backgroundColor = [ManagerEngine getColor:@"8ae6dc"];

            
        }
        
    }];
    
    RACSignal *idmergeSignal= [RACSignal combineLatest:@[idSignal]reduce:^id(NSNumber *idValid){
        return @([idValid boolValue]);
    }];

    [idmergeSignal subscribeNext:^(NSNumber *x) {
        if ([x boolValue]) {
            [self  idCardRequst];
        }
        
    }];
    
    
    RACSignal *MobilemergeSignal= [RACSignal combineLatest:@[newMoileSignal]reduce:^id(NSNumber *MoileValid){
        return @([MoileValid boolValue]);
    }];
    
    [MobilemergeSignal subscribeNext:^(NSNumber *x) {
        if ([x boolValue]) {
            [self  mobileReuqst];
        } else {
            _isMobileOk = NO;
        }
        
    }];
    
    
    [[self.okBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(id x) {
      
        
        [self okRequst];
        
    }];
    
    
    [self.codeBtn countDownButtonHandler:^(JKCountDownButton*sender, NSInteger tag) {
        
        if([ManagerEngine valiMobile:self.NewMobileTextField.text] == YES) {
            if (_isMobileOk == YES) {
                sender.enabled = NO;
                //        sender.backgroundColor = [ManagerEngine getColor:@"8ae6dc"];
                
                [sender startCountDownWithSecond:60];
                
                [sender countDownChanging:^NSString *(JKCountDownButton *countDownButton,NSUInteger second) {
                    NSString *title = [NSString stringWithFormat:@"剩余%zd秒",second];
                    return title;
                }];
                [RequestEngine HQJFacilitatorRequestDetailsUrl:[NSString stringWithFormat:@"%@getUpdateMobileSMS/mobile/%@",AppOrg_URL,self.NewMobileTextField.text] complete:^(NSDictionary *dic) {
                } andError:^(NSError *error) {
                    
                } ShowHUD:NO];
                [sender countDownFinished:^NSString *(JKCountDownButton *countDownButton, NSUInteger second) {
                    
                    countDownButton.enabled = YES;
                    return @"点击重新获取";
                    
                }];

            }
            
            
        }else {
            [ManagerEngine homeSvpStr:@"请核对手机号后重试" andcenterView:self.view andStyle:promptViewDefault];
            
        }
        
        
        
    }];

}

#pragma mark --
#pragma mark ---验证码位数判断
-(BOOL)codeValid:(NSString *)text {
    if (text.length == 4) {
        return YES;
    } else {
        return NO;
        
    }
    
    
    
}

#pragma mark --
#pragma mark ---密码位数判断
-(BOOL)pswValid:(NSString *)text {
    if(text.length == 6)  {
        return YES;
    } else {
        
        return NO;
    }

}

#pragma mark --
#pragma mark --- 提交
-(void)okRequst {
    
    NSString *urlStr = [NSString stringWithFormat:@"%@updateMobile/newMobile/%@/oldMobile/%@/tradepwd/%@/inputCode/%@/identitynum/%@",AppOrg_URL,self.NewMobileTextField.text,Mmobile,self.tradingPswTextField.text,self.codeTextField.text,self.idTextField.text];
    [RequestEngine HQJFacilitatorRequestDetailsUrl:urlStr complete:^(NSDictionary *dic) {
        
        if([dic[@"error"]integerValue] == 0) {
            [ManagerEngine customAlert:@"手机号修改成功" andViewController:self isBack:YES];
            [[NSNotificationCenter defaultCenter]postNotificationName:@"changeBonus" object:nil];

        }else {
            [ManagerEngine homeSvpStr:dic[@"result"][@"errmsg"]andcenterView:self.view andStyle:promptViewDefault];
            
        }
        
    } andError:^(NSError *error) {
        
    } ShowHUD:YES];
    
}

#pragma mark --
#pragma mark ---身份证验证请求
-(void)idCardRequst  {
    
    NSString *urlStr = [NSString stringWithFormat:@"%@judgeIdentitynum/oldMobile/%@/identitynum/%@",AppOrg_URL,Mmobile,_idTextField.text];
    [RequestEngine HQJFacilitatorRequestDetailsUrl:urlStr complete:^(NSDictionary *dic) {
        if([dic[@"error"]integerValue]!=0) {
//            HQJLog(@"身份验证：%@",dic[@"result"][@"errmsg"]);
            [ManagerEngine homeSvpStr:dic[@"result"][@"errmsg"] andcenterView:self.view andStyle:promptViewDefault];
        }
    } andError:^(NSError *error) {
        
    } ShowHUD:NO];

}


#pragma mark --
#pragma mark --- 手机号验证请求
-(void)mobileReuqst  {
    
    NSString *urlStr = [NSString stringWithFormat:@"%@judgeMobile/newMobile/%@",AppOrg_URL,_NewMobileTextField.text];
    [RequestEngine HQJFacilitatorRequestDetailsUrl:urlStr complete:^(NSDictionary *dic) {
        if([dic[@"error"]integerValue]!=0) {
            [ManagerEngine homeSvpStr:dic[@"result"][@"errmsg"] andcenterView:self.view andStyle:promptViewDefault];
        } else {
            _isMobileOk = YES;
        }
    } andError:^(NSError *error) {
        
    } ShowHUD:NO];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [self addUI];
    _isMobileOk = NO;
    [self initSignal];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
